<?php

namespace api\modules\tsline\models;

use Yii;
use common\base\Model;
use common\models\tsline\TslineArticleComment;
use common\models\tsline\TslineArticleStatistic;

class ArticleCommentForm extends Model {

    /**
     * @name $user_id
     * @var integer 用户UID
     */
    public $user_id;

    /**
     * @name $device_id
     * @var integer 设备ID
     */
    public $device_id;

    /**
     * @name $article_id
     * @var integer 被回复或评论的动态ID
     */
    public $article_id;

    /**
     * @name $comment_id
     * @var integer 被回复或评论的评论ID
     */
    public $comment_id = 0;

    /**
     * @name $content
     * @var string 回复或评论内容
     */
    public $content;

    /**
     * @name $images
     * @var array 回复或评论包含的图片集合
     */
    public $images = [];

    /**
     * @name $attachs
     * @var \common\models\Attachment 附件集合
     */
    private $attachs = null;

    public function rules() {
        return [
            [['user_id', 'device_id', 'article_id', 'comment_id'], 'integer'],
            [
                'content',
                'required',
                'when' => function ($model) {
                    return empty($model->images);
                },
                'message' => '{attribute}不能为空'
            ],
            [['content'], 'string', 'max' => 255],
            [['images'], 'validateAttachs'],
        ];
    }

    public function attributeLabels() {
        return [
            'content' => '评论内容'
        ];
    }

    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validateAttachs($attribute) {
        if (!$this->hasErrors() && !empty($this->$attribute)) {
            $this->attachs = Attachment::find()->where(['id' => $this->$attribute])->all();
        }
    }

    /**
     * 保存动态信息（发布&修改）
     * @param [type] $data
     * @return void
     */
    public function save() {
        if (!$this->validate()) {
            return $this->dumpError('发布提交失败');
        }

        $model = new TslineArticleComment();
        $model->attributes = [
            'article_id' => $this->article_id,
            'user_id' => $this->user_id,
            'device_id' => $this->device_id,
            'comment_id' => $this->comment_id,
            'content' => $this->content,
        ];
        if (!$model->save()) {
            return $this->dumpError('评论内容保存时失败' . print_r($model->errors, true));
        }

        $static = TslineArticleStatistic::findOrNew([
            'article_id' => $this->article_id
        ]);
        $static->comments += 1;
        $static->save(false);

        return [
            'award' => [
                'orange' => 2,
                'gold' => 2,
                'experience' => 100,
            ]
        ];
    }

}
